<div id="categories_viewer_modal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
        <%= render partial: 'help/help_categorize' %>
        <h3 id="myModalLabel"><i class="icon-th-large"></i><%= t("category.modalLabel") %></h3>
      </div>
      <div class="modal-body categorize-modal-body">
        <div class="row">
        <div class="col-md-6 selection_cat">
          <% generic_categories = Category.authored_by(current_subject).sort_by!{|e| e.title.downcase} %>
          <p class= "information"><%= t("category.cat_add_title") %></p>
          <% root_categories = generic_categories.reject{|n| n.parent_id != nil} %>

              <div id='jqxWidget'>
               <div id="dropDownButton">
                <div style="border: none;" id='jqxTree'>
                      <ul>
                        <% root_categories.each do |root_template| %>
                         <% html = '' %>
                            <ul>
                                <%= recursive_tree(root_template, html) %>
                            </ul>
                        <%end%>
                      </ul>
                  </div>
               </div>
              </div>

           <br>
           <p class="information"><%= t("category.cat_sugested")%></p>
           <div id="suggested_categories" class="tagBoxNew">
              <% rcCategories = generic_categories.reject{|e| get_initial_categories(item).include? e.id} %>
              <% simple_gen = rcCategories.sort{|a,b| b.property_objects.length <=> a.property_objects.length}.first(7)%>
              <ul id="suggestedCategories" class="tagit">
              <% simple_gen.each do |init| %>
                  <li class="tagit-choice" value="<%= init.id %>" ><%= init.title %></li>
              <% end %>
              </ul>

           </div>

          <% tagArray= generic_categories.map{|e| e.title} %>
          <% content_for :javascript do %>
              var tagList= [
                <% tagArray.each do |tags| %>
                  "<%= tags %>",
                <%end%>
              ];

              $("#myCategories").tagit({
                maxLength: 50,
                maxTags: 100000,
                triggerKeys: ['enter', 'tab'],
                watermarkAllowMessage: "<%= t('category.tagit_watermark_cat') %>",
                watermarkDenyMessage: '<%=t('document.tags.limitMessage')%>',
                tagSource: tagList
              });

              //Get categorized by this author
              <% resource_categories = []
              get_initial_categories(item).each do |e|
              n = Category.find(e)
                if generic_categories.include? n
                  resource_categories  += [n]
               end
              end
               %>
                <% resource_categories.each do |cat| %>
                  <% ident = Category.find(cat) %>
                  $("#myCategories").tagit("add", "<%= ident.title %>", "<%= ident.id %>");
              <% end %>
              //Save suggested categories state
          <%end%>


        </div>

        <div class="col-md-6">
          <p class="information"><%= t("category.categorized_like")%></p>
          <div class="tagBoxNew">
            <ul id="myCategories">
              <!-- Existing list items will be pre-added to the tags -->
            </ul>
          </div>
        </div>
      </div>

      </div>
      <div class="modal-footer">
        <button id="save_cat_button" class="btn btn-primary"><%= t('button.save')%></button>
      </div>
    </div>
  </div>

  <% content_for :javascript do %>

    //When click to suggested they go to down part for being categorized
    $("#suggested_categories li").click(function(){
      var value = $(this).val();
      var name = $(this).html();
      $("#myCategories").tagit("add", name, value);
    });

    //When saving gathering all tags and sending to server
    $("#save_cat_button").click(function() {
      var cat_done_array = [];

      $("#myCategories .tagit-choice").each(function(index,elem){
          cat_done_array.push({title: $(elem).text()});
      });

      $.ajax({
              url: '/categories/categorize',
              type: 'POST',
              dataType: "json",
              data: { activity_object_id:"<%=item.activity_object.id
    .to_s%>", category_array: JSON.stringify(cat_done_array) },
                success: function(data){
                  $("#categories_viewer_modal").modal('toggle');
                  //Emulating alert with javascript
                  $('#flash').hide();
                  $("#flash").append('<div class="alert alert-success"><button type="button" class="close" data-dismiss="alert">×</button><%=t("category.success")%></div>')
                              .fadeIn()
                              .delay(6000)
                              .fadeOut(300, function(){
                                $('#flash').html("");
                              });

                  },
                  error: function(){
                    $("#categories_viewer_modal").modal('toggle');
                    //Emulating alert with javascript
                    $('#flash').hide();
                    $("#flash").append('<div class="alert alert-success"><button type="button" class="close" data-dismiss="alert">×</button>Error</div>')
                              .fadeIn()
                              .delay(6000)
                              .fadeOut(300, function(){
                                $('#flash').html("");
                              });
                  }
      });
    });

    $("#cancel_cat_button").click(function() {
      $("#myCategories").tagit("reset");
      for (key in appliedTags){
        $("#myCategories").tagit("add",appliedTags[key]);
      }
      $("#categories_viewer_modal").modal('toggle');
    });

      var appliedTags = [];
      $('#categories_viewer_modal').on('shown', function() {
        $("#myCategories .tagit-choice").each(function(index,elem){
          appliedTags.push($(elem).text());
         });
        });

        // INITIALIZE TREE
        $("#dropDownButton").jqxDropDownButton({ width: 250, height: 25});
        $("#jqxTree").jqxTree({ width: 250, height: 220 });
        $('#jqxTree').jqxTree('collapseAll');
        $("#dropDownButton").jqxDropDownButton('setContent', '<div style="position: relative; margin-left: 3px; margin-top: 5px;"><%= t('document.help.categories1_html') %></div>');

        // DROPDOWN TREE CATEGORIES LOGIC
        $('#jqxTree').on('select', function (event) {
                  var args = event.args.element;
                  if (args.getAttribute("category_id") != null){

                  var value = args.getAttribute("category_id");
                  var name = $('#jqxTree').jqxTree('getItem', args).label;

                  $("#myCategories").tagit("add", name, value);
                  }

                  $('#dropDownButton').jqxDropDownButton('close');
       });

  <%end%>

</div>
